﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Controllers.Extend;
using Controllers.Filter;
using Model.Database;
using Model.Sys.Config;
using Newtonsoft.Json;
using SearchModel;
using ViewModel;

namespace Controllers.Areas.DataDictionary.Controllers
{
    public class ManagerController : UserBaseController
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            cookieName = CookieConfig.UserInfoLoginCookieName;
            base.OnAuthorization(filterContext);

            if (loginUser == null)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "对不起，您的身份验证过时，请重新登录。"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = "<script>alert('对不起，您的身份验证过时，请重新登录。');top.location='/Login/Index';</script>" };
                }
            }
        }

        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000500")]
        public ActionResult Index()
        {
            ViewData["PowerId"] = "01000500";
            return View();
        }

        /// <summary>
        /// 列表页面的列表查询
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public ActionResult HeadSearch(DataTable dt)
        {
            int total;
            int pageSize = dt.length;
            int pageIndex = dt.pageIndex;
            SMDataDictionaryHead smDataDictionaryHead = JsonConvert.DeserializeObject<SMDataDictionaryHead>(dt.searchStr);

            List<DataDictionaryHead> dataDictionaryHeadList=CurrentBllSession.DataDictionaryHeadBll.GetListBySearchPage(pageIndex,pageSize,out total,smDataDictionaryHead);
            dt.recordsTotal = total;
            dt.recordsFiltered = total;
            dt.data = dataDictionaryHeadList;

            return Json(dt);
        }

        /// <summary>
        /// 增加字典头页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000501")]
        public ActionResult AddHead()
        {
            return View();
        }

        /// <summary>
        /// 增加字典头提交
        /// </summary>
        /// <param name="pmDataDictionaryHead"></param>
        /// <returns></returns>
        public ActionResult AddHeadSubmit(DataDictionaryHead pmDataDictionaryHead)
        {
            ResultModel rm = new ResultModel();

            if (!string.IsNullOrEmpty(pmDataDictionaryHead.Name))
            {
                DataDictionaryHead dataDictionaryHead = pmDataDictionaryHead;

                if (CurrentBllSession.DataDictionaryHeadBll.GetIQueryable().Count(a => a.Name == dataDictionaryHead.Name)>0)
                {
                    rm.Pass = false;
                    rm.Msg = "字典头名称已存在";
                }
                else
                {
                    if (!dataDictionaryHead.Sort.HasValue)
                    {
                        dataDictionaryHead.Sort = MakeSortForHead();
                    }
                    dataDictionaryHead.AddTime = DateTime.Now;
                    CurrentBllSession.DataDictionaryHeadBll.Add(dataDictionaryHead);
                    CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
                    rm.Pass = true;
                    rm.Msg = "添加成功";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写完整信息";
            }

            return Json(rm);
        }

        /// <summary>
        ///  删除字典头
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000502")]
        public ActionResult DeleteHead(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            try
            {
                CurrentBllSession.DataDictionaryHeadBll.ListDelte(idArr);
                CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
                rm.Pass = true;
                rm.Msg = "删除成功";
            }
            catch (Exception ex)
            {
                rm.Pass = false;
                rm.Msg = "对不起，删除失败";
            }

            return Json(rm);
        }

        /// <summary>
        /// 修改字典头页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000503")]
        public ActionResult EditHead(int? id)
        {
            if (id.HasValue)
            {
                DataDictionaryHead dataDictionaryHead= CurrentBllSession.DataDictionaryHeadBll.GetEntity(id.Value);
                return View(dataDictionaryHead);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 修改字典头页面的提交
        /// </summary>
        /// <param name="pmDataDictionaryHead"></param>
        /// <returns></returns>
        public ActionResult EditHeadSubmit(DataDictionaryHead pmDataDictionaryHead)
        {
            ResultModel rm = new ResultModel();

            if ( (!string.IsNullOrEmpty(pmDataDictionaryHead.Name))  ||  (!pmDataDictionaryHead.Sort.HasValue)  )
            {
                DataDictionaryHead dataDictionaryHeadOld = CurrentBllSession.DataDictionaryHeadBll.GetEntity(pmDataDictionaryHead.DataDictionaryHeadId);
                if (CurrentBllSession.DataDictionaryHeadBll.GetIQueryable()
                    .Count(a => (a.Name == pmDataDictionaryHead.Name) && (a.DataDictionaryHeadId!=pmDataDictionaryHead.DataDictionaryHeadId) )>0) 
                {
                    rm.Pass = false;
                    rm.Msg = "字典头名已存在";
                }
                else 
                {
                    dataDictionaryHeadOld.Name = pmDataDictionaryHead.Name;
                    dataDictionaryHeadOld.Description = pmDataDictionaryHead.Description;
                    dataDictionaryHeadOld.Sort = pmDataDictionaryHead.Sort;
                    dataDictionaryHeadOld.ModifyTime = DateTime.Now;
                    CurrentBllSession.DataDictionaryHeadBll.Update(dataDictionaryHeadOld);
                    CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
                    rm.Pass = true;
                    rm.Msg = "保存成功";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写必要信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 查看字典项
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000504")]
        public ActionResult ViewItem(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                ViewData["dataDictionaryHead"]= CurrentBllSession.DataDictionaryHeadBll.GetEntity(int.Parse(id));
                return View();
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 禁用字典头
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000505")]
        public ActionResult ForbiddenHead(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.DataDictionaryHeadBll.ListForbidden(idArr);
            CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
            rm.Pass = true;
            rm.Msg = "禁用成功";

            return Json(rm);
        }

        /// <summary>
        /// 解禁字典头
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000506")]
        public ActionResult NoForbiddenHead(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.DataDictionaryHeadBll.ListNoForbidden(idArr);
            CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
            rm.Pass = true;
            rm.Msg = "解禁成功";

            return Json(rm);
        }

        /// <summary>
        /// 字典项列表查询
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public ActionResult ItemSearch(DataTable dt)
        {
            int total;
            int pageSize = dt.length;
            int pageIndex = dt.pageIndex;
            SMDataDictionaryItem smDataDictionaryItem = JsonConvert.DeserializeObject<SMDataDictionaryItem>(dt.searchStr);

            List<DataDictionaryItem> dataDictionaryItemList = CurrentBllSession.DataDictionaryItemBll.GetListBySearchPage(pageIndex, pageSize, out total, smDataDictionaryItem);
            dt.recordsTotal = total;
            dt.recordsFiltered = total;
            dt.data = dataDictionaryItemList;

            return Json(dt);
        }

        /// <summary>
        /// 增加字典项页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddItem(string dataDictionaryHeadId)
        {
            if (!string.IsNullOrEmpty(dataDictionaryHeadId))
            {
                ViewData["dataDictionaryHeadId"] = dataDictionaryHeadId;
                return View();
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 增加字典项页面的提交
        /// </summary>
        /// <param name="pmDataDictionaryItem"></param>
        /// <returns></returns>
        public ActionResult AddItemSubmit(DataDictionaryItem pmDataDictionaryItem)
        {
            ResultModel rm = new ResultModel();

            if (  !string.IsNullOrEmpty(pmDataDictionaryItem.Text)  )
            {
                DataDictionaryItem dataDictionaryItem = pmDataDictionaryItem;

                if (CurrentBllSession.DataDictionaryItemBll.GetIQueryable()
                    .Where(a=>a.DataDictionaryHeadId==pmDataDictionaryItem.DataDictionaryHeadId)
                    .Count(a => a.Text == pmDataDictionaryItem.Text) > 0 )
                {
                    rm.Pass = false;
                    rm.Msg = "文本或值已存在";
                }
                else
                {
                    if (!dataDictionaryItem.Sort.HasValue)
                    {
                        dataDictionaryItem.Sort = MakeSortForItem(dataDictionaryItem.DataDictionaryHeadId);
                    }
                    dataDictionaryItem.AddTime = DateTime.Now;
                    CurrentBllSession.DataDictionaryItemBll.Add(dataDictionaryItem);
                    CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
                    rm.Pass = true;
                    rm.Msg = "添加成功";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写完整信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 删除字典项
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        public ActionResult DeleteItem(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            try
            {
                CurrentBllSession.DataDictionaryItemBll.ListDelte(idArr);
                CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
                rm.Pass = true;
                rm.Msg = "删除成功";
            }
            catch (Exception ex)
            {
                rm.Pass = false;
                rm.Msg = "对不起，删除失败";
            }

            return Json(rm);
        }

        /// <summary>
        /// 修改字典项页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditItem(int? id)
        {
            if (id.HasValue)
            {
                DataDictionaryItem dataDictionaryItem = CurrentBllSession.DataDictionaryItemBll.GetEntity(id.Value);
                return View(dataDictionaryItem);
            }
            else
            {
                return Content("id参数无效");
            }
        }
        /// <summary>
        /// 修改字典项页面的提交
        /// </summary>
        /// <param name="pmDataDictionaryHead"></param>
        /// <returns></returns>
        public ActionResult EditItemSubmit(DataDictionaryItem pmDataDictionaryItem)
        {
            ResultModel rm = new ResultModel();

            if ((!string.IsNullOrEmpty(pmDataDictionaryItem.Text))  ||  (!pmDataDictionaryItem.Sort.HasValue))
            {
                DataDictionaryItem dataDictionaryItemOld = CurrentBllSession.DataDictionaryItemBll.GetEntity(pmDataDictionaryItem.DataDictionaryItemId);
                IQueryable<DataDictionaryItem> dataDictionaryItemIq= CurrentBllSession.DataDictionaryItemBll.GetIQueryable();
                if (dataDictionaryItemIq.Where(a=>a.DataDictionaryHeadId==dataDictionaryItemOld.DataDictionaryHeadId)
                    .Count(a=> (a.Text==pmDataDictionaryItem.Text) && (a.DataDictionaryItemId!=pmDataDictionaryItem.DataDictionaryItemId) )>0)
                {
                    rm.Pass = false;
                    rm.Msg = "文本或值已存在";
                }
                else
                {
                    dataDictionaryItemOld.Text = pmDataDictionaryItem.Text;
                    dataDictionaryItemOld.Description = pmDataDictionaryItem.Description;
                    dataDictionaryItemOld.Sort = pmDataDictionaryItem.Sort;
                    dataDictionaryItemOld.ModifyTime = DateTime.Now;
                    CurrentBllSession.DataDictionaryItemBll.Update(dataDictionaryItemOld);
                    CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
                    rm.Pass = true;
                    rm.Msg = "保存成功";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写必要信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 禁用字典项
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        public ActionResult ForbiddenItem(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.DataDictionaryItemBll.ListForbidden(idArr);
            CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
            rm.Pass = true;
            rm.Msg = "禁用成功";

            return Json(rm);
        }

        /// <summary>
        /// 解禁字典项
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        public ActionResult NoForbiddenItem(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.DataDictionaryItemBll.ListNoForbidden(idArr);
            CurrentBllSession.DataDictionaryHeadBll.ResetDataDictionary();
            rm.Pass = true;
            rm.Msg = "解禁成功";

            return Json(rm);
        }











        #region 私有方法
        /// <summary>
        /// 制作字典项排序号
        /// </summary>
        /// <param name="dataDictionaryItemId"></param>
        /// <returns></returns>
        private int MakeSortForItem(int dataDictionaryItemId)
        {
            int sort = 1;

            int? maxSort = CurrentBllSession.DataDictionaryItemBll.GetIQueryable().Where(a=>a.DataDictionaryHeadId==dataDictionaryItemId).Max(a => a.Sort);
            if (maxSort.HasValue)
            {
                sort = maxSort.Value + 1;
            }

            return sort;
        }
        /// <summary>
        /// 制作字典头排序号
        /// </summary>
        /// <returns></returns>
        private int MakeSortForHead()
        {
            int sort = 1;

            int? maxSort = CurrentBllSession.DataDictionaryHeadBll.GetIQueryable().Max(a => a.Sort);
            if (maxSort.HasValue)
            {
                sort = maxSort.Value+1;
            }

            return sort;
        }
        #endregion


    }
}
